﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Ivy.Common.Framework.GeneralUtility; //needed for all UI for exception handling

using System.Net;
using System.Net.Mail;
using Ivy.UserRegistration.BusinessLogic;
using Ivy.UserRegistration.Entity;
using Ivy.Common.Framework.EmailUtility; //To be removed


namespace DasIdeen.Pages
{
    public partial class TestingPageForMrinmoy : System.Web.UI.Page
    {
        
        #region  Variable & constant
        //All constants and local variable should be declared here
        #endregion  Variable & constant

        #region Constructor & Destructor
        //Generally not needed in UI layer
        #endregion Constructor & Destructor

        #region Properties
        //UI layer may have public custom properties. these are very handy for User Controls
        #endregion Properties

        #region Public Methods
        //UI layer may have public custom properties. these are very handy for User Controls
        #endregion Public Methods

        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            try //All events in pages or user control should have try{} catch {} block.
            {
                //First check if the current logged in user is having proper role/authorization to access this page or not.
                if (IsUserAutherization())
                {
                    //TODO - Your code to display the initial layout/data etc.
                }
                else
                {
                    //TODO - Your code to redirect page to "NOT AUTHORIZED" page or any other page as required by the business logic.
                }
            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }
        }
        protected void chkUseDefaultCredentials_CheckedChanged(object sender, EventArgs e)
        {

        }

        protected void optConfigFileGoogleMailSetting_CheckedChanged(object sender, EventArgs e)
        {
            if (this.optConfigFileGoogleMailSetting.Checked)
            {
                string lConfigSmtpSettingName = "GoogleMailServer";
                //GetSmtpServerDetailsFromConfigFile(lConfigSmtpSettingName);
            }
        }

        protected void optConfigFileGoDaddyMailSetting_CheckedChanged(object sender, EventArgs e)
        {
            if (this.optConfigFileGoDaddyMailSetting.Checked)
            {
                string lConfigSmtpSettingName = "GodaddyDasIdeenAdminMailServer";
                //GetSmtpServerDetailsFromConfigFile(lConfigSmtpSettingName);
            }
        }

        protected void chkUseConfigFile_CheckedChanged(object sender, EventArgs e)
        {
            if (this.chkUseConfigFile.Checked)
            {
                this.optUseGoogle.Enabled = false;
                this.optUseGoddayRelayHost.Enabled = false;
                this.optUseGodaddyDomailHost.Enabled = false;
                //this.optConfigFileGoogleMailSetting.Enabled = !this.chkUseConfigFile.Checked;
                //this.optConfigFileGoDaddyMailSetting.Enabled = !this.chkUseConfigFile.Checked;

                UserRegistrationBus lUserRegistrationBus = new UserRegistrationBus();
                User lUser = lUserRegistrationBus.GetUserByLoginID("mrinmoyd");
                MailMessage lMailMessage = CreateMailBody(lUser);
                EmailUtility lEmailUtility = new EmailUtility();
                SmtpClient smtpClientObject = lEmailUtility.GetSmptClient();
                this.chkSmtpHostSSL.Checked = smtpClientObject.EnableSsl;
                this.txtSmtpHost.Text = smtpClientObject.Host;
                this.txtSmtpPort.Text = smtpClientObject.Port.ToString();
                this.chkUseDefaultCredentials.Checked = smtpClientObject.UseDefaultCredentials;
                NetworkCredential lNetworkCredential = smtpClientObject.Credentials.GetCredential(smtpClientObject.Host,smtpClientObject.Port,"");
                this.txtUserId.Text = lNetworkCredential.UserName;
                this.txtPassword.Text = lNetworkCredential.Password;
                lEmailUtility.SendEmail(smtpClientObject, lMailMessage);
            }
            else
            {
                this.optUseGoogle.Enabled = true;
                this.optUseGoddayRelayHost.Enabled = true;
                this.optUseGodaddyDomailHost.Enabled = true;
            }
        }

        protected void optUseGoogle_CheckedChanged(object sender, EventArgs e)
        {
            if (this.optUseGoogle.Checked)
            {
                //this.optUseGodaddyDomailHost.Checked = false;
                //this.optUseGoddayRelayHost.Checked = false;
                lblResult.Text = "Using Google Mail SMTP host";
                this.txtSubject.Text = "Framework Test Mail service [Using Google Mail SMTP host]";
                this.txtMailFrom.Text = "frameworkivy@gmail.com";
                this.chkSmtpHostSSL.Checked = true;
                this.txtSmtpHost.Text = "smtp.gmail.com";
                this.txtSmtpPort.Text = "587";
                this.chkUseDefaultCredentials.Checked = false;
                this.txtUserId.Text = "frameworkivy";
                this.txtPassword.Text = "frameworkivy12";
            }
        }

        protected void optUseGodaddyDomailHost_CheckedChanged(object sender, EventArgs e)
        {
            if (this.optUseGodaddyDomailHost.Checked)
            {
                //this.optUseGoddayRelayHost.Checked = false;
                //this.optUseGoddayRelayHost.Checked = false;
                lblResult.Text = "Using GoDaddy Domain Mail SMTP host";
                this.txtSubject.Text = "Framework Test Mail service [Using GoDaddy Domain Mail SMTP host]";
                this.txtMailFrom.Text = "administrator@dasideen.com";
                this.chkSmtpHostSSL.Checked = false;
                this.txtSmtpHost.Text = "smtpout.asia.secureserver.net";
                this.txtSmtpPort.Text = "25";
                this.chkUseDefaultCredentials.Checked = false;
                this.txtUserId.Text = "administrator@dasideen.com";
                this.txtPassword.Text = "dasideen@";
            }
        }

        protected void optUseGoddayRelayHost_CheckedChanged(object sender, EventArgs e)
        {
            if (this.optUseGoddayRelayHost.Checked)
            {
                //this.optUseGodaddyDomailHost.Checked = false;
                //this.optUseGoogle.Checked = false;
                lblResult.Text = "Using GoDaddy Relay Mail SMTP host";
                this.txtSubject.Text = "Framework Test Mail service [Using GoDaddy Relay Mail SMTP host]";
                this.txtMailFrom.Text = "administrator@dasideen.com";
                this.chkSmtpHostSSL.Checked = false;
                this.txtSmtpHost.Text = "relay-hosting.secureserver.net";
                this.txtSmtpPort.Text = "25";
                this.chkUseDefaultCredentials.Checked = true;
                this.txtUserId.Text = "administrator@dasideen.com";
                this.txtPassword.Text = "dasideen@";
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            SendMail();
        }
        #endregion Events

        #region Private Methods

        /// <summary>
        /// This method is to check if the current logged in user is having proper role/authorization to access this page or not.
        /// </summary>
        private bool IsUserAutherization()
        {
            bool _IsUserAutherization = false;
            //TODO - Your code to check authorization goes here.

            //for the time being let us allow the user to access this page.
            //but remove the below line once you have a proper logic.
            _IsUserAutherization = true;

            return _IsUserAutherization;
        }


        /// <summary>
        /// This method is to clear all UI controls which are data binded.
        /// </summary>
        private void ClearScreen()
        {
        }

       
        /// <summary>
        /// This method is to bind all the UI control like dropdown list or list box etc with the required initial data, 
        /// </summary>
        private void FillLoadLookUpData()
        {
        }

        /// <summary>
        /// This method is to load the UI with initial set of data based of the business logic.
        /// </summary>
        private void InitializeScreen()
        {
            ClearScreen();
            FillLoadLookUpData();
        }

        /// <summary>
        /// This method is to copy the entity properties that need to be displayed in the UI controls to the UI control.
        /// Example - [pUser] is an instance of an entity and is filled with specific USER data.
        /// and this user instance is to be displayed is an UI control text boxes.
        /// A sample code will look like the following:
        ///  this.txtFirstName.Text = pUser.UserFirstName; 
        ///  this.txtLastName.Text  = pUser.UserLastName; 
        ///  this.txtLoginId.Text   = pUser.UserLoginID;
        /// </summary>
        private void TranslateEntityToUIControls()
        {
        }

        /// <summary>
        /// This method is to copy the user entered data from the UI controls to the entity instance that will be used to sent the entity to any other layer.
        /// Example - [pUser] is an instance of an entity and is to be filled with specific USER data that has been captured in the screen.
        /// A sample code will look like the following:
        ///  pUser.UserFirstName = this.txtFirstName.Text; 
        ///  pUser.UserLastName  = this.txtLastName.Text; 
        ///  pUser.UserLoginID   = this.txtLoginId.Text; 
        /// </summary>
        private void TranslateUIControlsToEntity()
        {
        }

        private void SendMailUsingGodaddyHost()
        {
            try
            {

                //Create the msg object to be sent
                MailMessage msg = new MailMessage();
                //Add your email address to the recipients
                msg.To.Add("mrinmoyd@hotmail.com");
                //Configure the address we are sending the mail from
                MailAddress address = new MailAddress("mr@soundout.net");
                msg.From = address;
                msg.Subject = "Test Mail send from GODADDY Host";
                msg.Body = msg.Subject + "n" + msg.Subject + "n" + msg.Subject;

                SmtpClient client = new SmtpClient();
                client.Host = "relay-hosting.secureserver.net";
                client.Port = 25;

                //Send the msg
                client.Send(msg);

                //Display some feedback to the user to let them know it was sent
                lblResult.Text = "Your message was sent!";
            }
            catch (Exception ex)
            {
                //If the message failed at some point, let the user know
                lblResult.Text = ex.ToString(); //alt text "Your message failed to send, please try again."
            }
        }

        private void SendMail()
        {
            try
            {
                //Create the msg object to be sent
                MailMessage msg = new MailMessage();
                //Add your email address to the recipients
                if (this.txtMailTo.Text != string.Empty)
                {
                    msg.To.Add(this.txtMailTo.Text);
                    if (this.txtMailCC.Text.Trim() != string.Empty)
                    {
                        msg.CC.Add(this.txtMailCC.Text);
                    }
                    if (this.txtMailBCC.Text.Trim() != string.Empty)
                    {
                        msg.Bcc.Add(this.txtMailBCC.Text);
                    }
                    if (this.txtMailFrom.Text != string.Empty)
                    {
                        //Configure the address we are sending the mail from
                        MailAddress address = new MailAddress(this.txtMailFrom.Text, this.txtMailFrom.Text);
                        msg.From = address;
                        msg.Subject = this.txtSubject.Text;
                        msg.Body = this.txtBody.Text;

                        //Configure an SmtpClient to send the mail.            
                        SmtpClient client = new SmtpClient();
                        client.DeliveryMethod = SmtpDeliveryMethod.Network;

                        client.UseDefaultCredentials = this.chkUseDefaultCredentials.Checked;
                       
                        //Setup credentials to login to our sender email address ("UserName", "Password")
                        if (this.txtUserId.Text != string.Empty)
                        {
                            if (this.txtPassword.Text != string.Empty)
                            {
                                NetworkCredential credentials = new NetworkCredential(this.txtUserId.Text, this.txtPassword.Text);
                                client.Credentials = credentials;
                               


                                client.EnableSsl = this.chkSmtpHostSSL.Checked;
                                if (this.txtSmtpHost.Text != string.Empty)
                                {
                                    client.Host = this.txtSmtpHost.Text;
                                    if (this.txtSmtpPort.Text != string.Empty)
                                    {
                                        client.Port = Convert.ToInt32(this.txtSmtpPort.Text);

                                        //Send the msg
                                        client.Send(msg);

                                        //Display some feedback to the user to let them know it was sent
                                        lblResult.Text = "Your message was sent!";
                                    }
                                    else
                                    {
                                        lblResult.Text = "Empty SMTP host server port";
                                    }
                                }
                                else
                                {
                                    lblResult.Text = "Empty SMTP host server name";
                                }
                            }
                            else
                            {
                                lblResult.Text = "Empty Network Credential Password";
                            }
                        }
                        else
                        {
                            lblResult.Text = "Empty Network Credential User ID";
                        }
                    }
                    else
                    {
                        lblResult.Text = "Empty From mail Address";
                    }
                }
                else
                {
                    lblResult.Text = "Empty Send mail Address";
                }
            }
            catch (Exception ex)
            {
                //If the message failed at some point, let the user know
                lblResult.Text = ex.ToString();
                //"Your message failed to send, please try again."
            }

        }

        private MailMessage CreateMailBody(User UserEntity)
        {
            EmailUtility lEmailUtility = new EmailUtility();
            MailMessage lMailMsg = new MailMessage();
            lMailMsg.Subject = "Dasideen - Registration verification & confirmation mail";
            lMailMsg.IsBodyHtml = true;
            lMailMsg.Body = @"<html xmlns=""http://www.w3.org/1999/xhtml"" xml:lang=""en"">";
            lMailMsg.Body = lMailMsg.Body + @"<head> <style type=""text/css""> .style1 { color: #006600; } .style2 { text-align: left; font-size: small; } .style3 { font-size: large; } .style4 { font-size: large; font-weight: bold; } </style> </head>";
            lMailMsg.Body = lMailMsg.Body + @"<body style=""font-family: 'MS Sans Serif'; text-align: center"">";
            lMailMsg.Body = lMailMsg.Body + @"<table class=""style3"">";
            lMailMsg.Body = lMailMsg.Body + @"<tr><td><h1 class=""style1""> Congratulation ! </h1></td></tr>";
            lMailMsg.Body = lMailMsg.Body + @"<tr><td class=""style3""> You have Successfully Registered with Dasideen. </td></tr>";
            lMailMsg.Body = lMailMsg.Body + @"<tr><td class=""style3""> Please Note Following : </td></tr>";
            lMailMsg.Body = lMailMsg.Body + @"<tr><td><span class=""style3"">User Name : </span><span class=""style4"">" + UserEntity.UserFirstName + " " + UserEntity.UserLastName + @"</span><span class=""style3""> </span></td></tr>";
            lMailMsg.Body = lMailMsg.Body + @"<tr><td><span class=""style3"">User Login Id : </span><span class=""style4"">" + UserEntity.UserLoginID + @"</span><span class=""style3""> </span></td></tr>";
            lMailMsg.Body = lMailMsg.Body + @"<tr> <td> <span class=""style3"">User Verification Code : </span><span class=""style4"">" + UserEntity.UserVerificationCode + @"</span><span class=""style3""> </span> </td> </tr>";
            lMailMsg.Body = lMailMsg.Body + @"<tr> <td class=""style3""> To activate your membership, please login and confirm your verification code </td></tr>";
            lMailMsg.Body = lMailMsg.Body + @"<tr> <td> &nbsp; </td> </tr>";
            lMailMsg.Body = lMailMsg.Body + @"<tr> <td class=""style2""> Thanks and Regards </td> </tr> <tr> <td class=""style2""> Dasideen(The Ideas) Administrator </td> </tr> <tr> <td class=""style2""> (A Crowd Community) </td> </tr> <tr> <td class=""style2""> &nbsp; </td> </tr>";
            //lMailMsg.Body = lMailMsg.Body + @"<tr> <td class=""style2""> Follow our project at CodePlex <a href=""http://ivyframeworks.codeplex.com/""> www.ivyframeworks.codeplex.com/</a> </td> </tr>";
            lMailMsg.Body = lMailMsg.Body + @"<tr> <td class=""style2""> Copyright &copy; 2012&nbsp; <a href=""http://www.dasideen.com/"">www.dasideen.com</a> </td></tr>";
            lMailMsg.Body = lMailMsg.Body + @"</table></body></html>";

            //lEmailUtility.AddEmailSenderAddressToMailMessage(lMailMsg, "frameworkivy@gmail.com", "Administrator FrameworkIvy");
            //lEmailUtility.AddEmailRecepientOrReplyAddressesToMailMessage(lMailMsg, EmailAddressType.SendTo, UserEntity.UserPrimaryEmailID);
            //lEmailUtility.AddEmailRecepientOrReplyAddressesToMailMessage(lMailMsg, EmailAddressType.SendBcc, "frameworkivy@googlegroups.com");

            lEmailUtility.AddEmailSenderAddressToMailMessage(lMailMsg);
            lEmailUtility.AddEmailRecepientOrReplyAddressesToMailMessage(lMailMsg, EmailAddressType.SendTo, UserEntity.UserPrimaryEmailID);
            lEmailUtility.AddEmailRecepientForAdminGroupToMailMessage(lMailMsg);

            lblResult.Text = "Using Web Config settings";
            
            this.txtSubject.Text = lMailMsg.Subject;
            this.txtMailFrom.Text = lMailMsg.From.Address;
            this.txtMailTo.Text = lMailMsg.To[0].Address;
            //this.txtMailCC.Text = lMailMsg.CC[0].Address;
            this.txtMailBCC.Text = lMailMsg.Bcc[0].Address;
            return lMailMsg;
        }
            
        #endregion Private Methods

    }
}